/*
 * @Author: fleeting-ln 3518413017@qq.com
 * @Date: 2023-11-28 23:16:13
 * @LastEditors: fleeting-ln 3518413017@qq.com
 * @LastEditTime: 2023-12-08 00:46:29
 * @FilePath: \see_you\src\store\modules\list.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/***
 * @Author: XY
 * @Date: 2023-11-14 16:52:41
 * @LastEditors: XY
 * @LastEditTime: 2023-11-16 10:38:13
 * @FilePath: \friendsApp\see_you\src\store\modules\siteConfig.js
 **/

import {
  formatTime
} from '@/utils/fun'
import WebIM from '@/utils/WebIM';
import { enterim } from '@/api/index'
import store from '@/store';
import { generateUUID } from '@/utils/fun'
import router from '@/router/index'

const state = {
  //当前登录用户的环信会话最新的信息
  channel_infos: {},
  infoObj: '',
  UserChattingRecord: '', //用户的聊天会话
  options: {
    // 对方的用户 ID 或者群组 ID 或聊天室 ID。
    targetId: '',
    // 每页期望获取的消息条数。取值范围为 [1,50]，默认值为 20。
    pageSize: 20,
    // 查询的起始消息 ID。若该参数设置为 `-1`、`null` 或空字符串，从最新消息开始。
    cursor: -1,
    // 会话类型：（默认） `singleChat`：单聊；`groupChat`：群聊。
    chatType: "singleChat",
    // 消息搜索方向：（默认）`up`：按服务器收到消息的时间的逆序获取；`down`：按服务器收到消息的时间的正序获取。
    searchDirection: "up",
  },
  messages: {
    messages: []
  }, //获取当前用户的会话；
  systemmessages: {}, //系统会话
  systeid: 'system_message_user', //系统环信id
  searchParameter: { //获取会话列表的分页
    pageSize: 20,
    cursor: 1,
  },
  sessionlist: [], //获取最新的会话列表
}
const getters = {
  channel_infos: state => state.channel_infos,
  infoObj: state => state.infoObj,
  UserChattingRecord: state => state.UserChattingRecord,
  options: state => state.options,
  messages: state => state.messages,
  systemmessages: state => state.systemmessages,
  searchParameter: state => state.searchParameter,
  sessionlist: state => state.sessionlist,
}

const mutations = {
  SET_sessionlist: (state, data) => {
    state.sessionlist = data
  },
  SET_searchParameter: (state, data) => {
    state.searchParameter = data
  },
  SET_systemmessages: (state, data) => {
    state.systemmessages = data
  },
  SET_CHANNEL_INFOS: (state, data) => {
    state.channel_infos = data
  },
  SET_INFOOBJ: (state, data) => {
    state.infoObj = data
  },
  SET_UserChattingRecord: (state, data) => {
    state.UserChattingRecord = data
  },
  SET_options: (state, data) => {
    state.options = data
  },
  SET_messages: (state, data) => {
    state.messages = data
  },
}

const actions = {
  // 获取系统的会话列表
  getSystemData(context) {
    let options = {
      // 对方的用户 ID 或者群组 ID 或聊天室 ID。
      targetId: context.state.systeid,
      // 每页期望获取的消息条数。取值范围为 [1,50]，默认值为 20。
      pageSize: 20,
      // 查询的起始消息 ID。若该参数设置为 `-1`、`null` 或空字符串，从最新消息开始。
      cursor: -1,
      // 会话类型：（默认） `singleChat`：单聊；`groupChat`：群聊。
      chatType: 'singleChat',
      // 消息搜索方向：（默认）`up`：按服务器收到消息的时间的逆序获取；`down`：按服务器收到消息的时间的正序获取。
      searchDirection: 'up',
    }
    WebIM.conn.getHistoryMessages(options).then((res) => {
      // 成功获取历史消息。
      console.log(res)
      if (res.messages.length > 0) {
        res.messages[0].time = formatTime(res.messages[0].time)
        context.commit('SET_systemmessages', {
          ...res.messages[0],
          unread_num: res.messages.length,
        });
      }
    })
  },
  //   {
  //     "id": "1221468402514658768",
  //     "type": "txt",
  //     "chatType": "singleChat",
  //     "msg": "我",
  //     "to": "164",
  //     "from": "177",
  //     "ext": {},
  //     "time": "刚刚",
  //     "onlineState": 3,
  //     "userInfo": {
  //         "164": {
  //             "avatarurl": "https://static.seyou1.vip/avatar/20230801/d6d0b202308011337557014.jpeg",
  //             "nickname": "张肥肥"
  //         },
  //         "177": {
  //             "avatarurl": "https://static.seyou1.vip/avatar/20231112/d1a14202311122117082500.jpeg",
  //             "nickname": "西城客"
  //         }
  //     }
  // }
  //重新,获取会话列表以及会话中的最新一条消息；
  regaingetConversationlist(context, value) {
    console.log(value);
    let sessionlist = context.state.sessionlist;
    for (let index = 0; index < sessionlist.length; index++) {
      const element = sessionlist[index];
      if (value.to == element.key || value.from == element.key) {
        sessionlist[index].lastMessage = value;
      }
    }
    context.commit('SET_sessionlist', sessionlist);
  },
  //获取会话列表以及会话中的最新一条消息；
  getConversationlist(context) {
    return new Promise((resolve, reject) => {
      WebIM.conn.getConversationlist({
        ...context.state.searchParameter,
      }).then(async (res) => {
        if (res.data.channel_infos.length > 0) {
          console.log(res)
          let list = []
          for (
            let index = 0; index < res.data.channel_infos.length; index++
          ) {
            const element = res.data.channel_infos[index]
            let users = ''
            if (store.state.userInfo.uid != element.lastMessage.from) {
              users = element.lastMessage.from
            } else {
              users = element.lastMessage.to
            }

            if (element.lastMessage.type == 'img') {
              var options = {
                url: element.lastMessage.url
              };
              options.onFileDownloadComplete = function (data) {
                //图片下载成功，需要将data转换成blob，使用objectURL作为img标签的src即可。
                var objectURL = WebIM.utils.parseDownloadResponse.call(WebIM.conn, data);
                element.lastMessage.url = objectURL;
                console.log(objectURL)
              }
              options.onFileDownloadError = function () {
                // 图片下载失败
                console.log('下载失败');
              };
              WebIM.utils.download.call(WebIM.conn, options);
            }

            element.lastMessage.time = formatTime(element.lastMessage.time)

            await WebIM.conn.fetchUserInfoById(users).then((ress) => {
              element['userInfo'] = ress.data
              element['key'] = users;
            })
            list.push(element)
          }

          context.state.sessionlist = context.state.sessionlist.concat(list)
          context.state.searchParameter.cursor++
        } else {
          context.state.searchParameter.cursor--
        }
        if (res.data.channel_infos.length <= context.state.searchParameter.pageSize) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((err) => {
        reject(err)
        // this.getData();
      })
    })
  },
  //   {
  //     "id": "1221462172136113580",
  //     "type": "txt",
  //     "chatType": "singleChat",
  //     "msg": "发一条",
  //     "to": "164",
  //     "from": "177",
  //     "ext": {},
  //     "time": 1701958623755,
  //     "onlineState": 3
  // }
  //接收最新的消息，并push到消息列表末尾
  defaultData(context, value) {
    let messages = context.state.messages;

    value.time = formatTime(value.time)
    value.userInfo = messages.messages[0].userInfo

    messages.cursor = value.id
    messages.messages.push(value)

    // options.cursor = -1;
    context.commit('SET_messages', messages);
    // context.commit('SET_options', options);
    // context.dispatch("defaultData")
  },
  //获取当前用户的聊天记录
  getUserChattingRecord(context) {
    console.log("执行");
    return new Promise(async (resolve, reject) => {
      let options = context.state.options;
      if (context.state.messages.cursor) {
        options.cursor = context.state.messages.cursor;
      }

      options.targetId = context.state.infoObj.key.toString();
      console.log(WebIM);
      await WebIM.conn.getHistoryMessages(options).then(async (res) => {
        // 成功获取的历史消息。
        if (res.messages.length > 0) {
          let is = true;
          let userInfo = ''
          console.log(res)
          for (let index = 0; index < res.messages.length; index++) {
            const element = res.messages[index];
            let users = [element.to, element.from];
            element.time = formatTime(element.time)

            if (element.type == 'img') {
              var optionss = {
                url: element.url
              };
              optionss.onFileDownloadComplete = function (data) {
                //图片下载成功，需要将data转换成blob，使用objectURL作为img标签的src即可。
                var objectURL = WebIM.utils.parseDownloadResponse.call(WebIM.conn, data);
                element.url = objectURL;
                console.log(objectURL)
              }
              optionss.onFileDownloadError = function () {
                // 图片下载失败
                console.log('下载失败');
              };
              WebIM.utils.download.call(WebIM.conn, optionss);
            }

            if (is) {
              await WebIM.conn.fetchUserInfoById(users).then(ress => {
                element['userInfo'] = ress.data;
                userInfo = ress.data;
                is = false;
              })
            } else {
              element['userInfo'] = userInfo;
            }
          }

          if (res.messages.length == context.state.options.pageSize) {
            resolve(true);
            // options.cursor = res.messages[0].id
          } else {
            resolve(false);
          }
          // if (!res.isLast) {
          //   resolve(true);
          //   // options.cursor++;
          // }else{
          //   resolve(false);
          // }
          // console.log(context.state.messages);
          let messages = res;
          //倒序数组
          messages.messages = messages.messages.reverse();
          messages.messages = res.messages.concat(...context.state.messages.messages);
          context.commit('SET_messages', messages);
          context.commit('SET_options', options);
        } else {
          resolve(false);
        }
      }).catch((e) => {
        console.log(e);
        // 获取失败。
      })
    })
  },
  login() {
    return new Promise((resolve, reject) => {
      enterim().then(ress => {
        store.commit('SET_ACCESS_TOKEN', ress.data.access_token)
        console.log(store.state.userInfo.uid.toString());
        console.log(store.state.access_token);
        WebIM.conn.open({
          user: store.state.userInfo.uid.toString(),
          accessToken: store.state.access_token,
        }).then(() => {
          console.log("登录成功");
          // let path = router.app.$router.currentRoute.path;
          // router.push({ path: path })
          resolve(true);
        }).catch((reason) => {
          console.log(reason);
          store.commit('SET_TOKEN', '');
          store.commit('SET_DID', '');
          store.commit('SET_APP_KEY', '');
          generateUUID();
          //跳转到登录页面
          router.replace('/Login')
          reject(err)
        });
      })
    })
  }
}
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}